package com.qlc_demo_api.filter;

import com.alibaba.fastjson.JSONObject;
import com.qlc_demo_api.shiro.JWTToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class JWTFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public JWTFilter() {
        super();
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 允许客户端，处理一个新的响应头jwt
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "etoken");

        if(httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 执行登录操作
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        logger.info("JwtFilter -----> executeLogin() 方法执行");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String etoken = httpServletRequest.getHeader("User-Token");
        JWTToken jwtToken = new JWTToken(etoken);
        logger.info("-----执行登陆开始-----");
        try {
            getSubject(request, response).login(jwtToken);
        }catch (AuthenticationException e) {
            e.printStackTrace();
            responseError(response, "etoken 验证失败");
            return false;
        }
        logger.info("-----执行登陆结束----- 未抛出异常");
        return true;
    }

    /**
     * 如果带有 etoken，则对 etoken 进行检查，否则直接通过
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        logger.info("JwtFilter -----> isAccessAllowed() 方法执行");
        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
                return true;
            }catch (Exception e) {
                responseError(response, e.getMessage());
                return false;
            }
        }else {
            responseError(response, "etoken not in");
            return false;
        }
//        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String etoken = req.getHeader("User-Token");

        return etoken != null;
    }

    /**
     *  isAccessAllowed()返回false便会执行这个方法，
     * @param request
     * @param response
     * @return 返回false，则过滤器的流程结束且不会执行访问controller的方法
     * @throws Exception
     */
    @Override
    public boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

    private void responseError(ServletResponse response, String message) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            if (message.contains("etoken") && httpServletResponse != null) {
//                String encodingMsg = URLEncoder.encode(message, "UTF-8");
//                httpServletResponse.sendError(200, encodingMsg);

                httpServletResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = httpServletResponse.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("status", 401);
                map.put("message", message);
                map.put("refreshToken", true);
                out.write(JSONObject.toJSONString(map));
                out.flush();
                out.close();
                return;
            }
            httpServletResponse.sendError(402, message);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
